<script setup lang="ts">
import { computed, ref } from 'vue';

import { useVbenDrawer } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { cloneDeep } from '@vben/utils';

import { useVbenForm } from '#/adapter/form';
import {
  sourceTrackAdd,
  sourceTrackInfo,
  sourceTrackUpdate,
} from '#/api/register/track';
import { dictDataInfo } from '#/api/system/dict/dict-data';
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';

import { drawerSchema } from './data';

const emit = defineEmits<{ reload: [] }>();

const isUpdate = ref(false);
const title = computed(() => {
  return isUpdate.value ? $t('pages.common.edit') : $t('pages.common.add');
});

const [BasicForm, formApi] = useVbenForm({
  commonConfig: {
    // 默认占满两列
    formItemClass: 'col-span-2',
    // 默认label宽度 px
    labelWidth: 120,
    // 通用配置项 会影响到所有表单项
    componentProps: {
      class: 'w-full',
    },
  },
  schema: drawerSchema(),
  showDefaultActions: false,
  wrapperClass: 'grid-cols-2',
});

const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
  {
    initializedGetter: defaultFormValueGetter(formApi),
    currentGetter: defaultFormValueGetter(formApi),
  },
);

const [BasicDrawer, drawerApi] = useVbenDrawer({
  // 在这里更改宽度
  class: 'w-[700px]',
  onBeforeClose,
  onClosed: handleClosed,
  onConfirm: handleConfirm,
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null;
    }
    drawerApi.drawerLoading(true);

    const { id } = drawerApi.getData() as { id?: number | string };
    isUpdate.value = !!id;

    formApi.updateSchema([
      {
        fieldName: 'appId',
        componentProps: {
          onChange: async (e: any) => {
            resetOldUrl();
            const list = (await dictDataInfo(e.target.value)) ?? [];
            formApi.updateSchema([
              {
                fieldName: 'oldUrl',
                componentProps: {
                  options: list.map((item) => {
                    return {
                      label: `${item.dictLabel} ${item.dictValue}`,
                      value: (item.dictValue || '').split('?')[0],
                      title: item.dictLabel,
                    };
                  }),
                },
              },
            ]);
          },
        },
      },
    ]);

    if (isUpdate.value && id) {
      const record = await sourceTrackInfo(id);
      await formApi.setValues(record);
    }
    await markInitialized();

    drawerApi.drawerLoading(false);
  },
});

function resetOldUrl() {
  formApi.updateSchema([
    { fieldName: 'oldUrl', componentProps: { options: [] } },
  ]);
}

async function handleConfirm() {
  try {
    drawerApi.lock(true);
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    // getValues获取为一个readonly的对象 需要修改必须先深拷贝一次
    const data = cloneDeep(await formApi.getValues());
    if (data.oldUrl?.includes('?')) {
      data.oldUrl = data.oldUrl.split('?')[0];
    }
    await (isUpdate.value ? sourceTrackUpdate(data) : sourceTrackAdd(data));
    resetInitialized();
    emit('reload');
    drawerApi.close();
  } catch (error) {
    console.error(error);
  } finally {
    drawerApi.lock(false);
  }
}

async function handleClosed() {
  await formApi.resetForm();
  resetInitialized();
}
</script>

<template>
  <BasicDrawer :title="title">
    <BasicForm />
  </BasicDrawer>
</template>
